<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模板名称" prop="templateName">
        <el-input
          v-model="queryParams.templateName"
          placeholder="请输入模板名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-tabs v-model="queryType" type="card" @tab-click="handleClick">
      <el-tab-pane label="公司模板" name="公司模板">
      </el-tab-pane>
      <el-tab-pane label="平台模板" name="平台模板">
      </el-tab-pane>
    </el-tabs>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="jumpDZQ"
          v-hasPermi="['system:template:add']"
        >上传模版</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="templateList">
      <el-table-column :formatter="defaultTableColumnDate" label="ID" align="center" prop="id" />
      <el-table-column :formatter="defaultTableColumnDate" label="合同模版名称" align="center" prop="templateName" />
      <!-- <el-table-column :formatter="defaultTableColumnDate" label="模版描述" align="center" prop="remark" v-if="queryType=='平台模板'" /> -->
      <el-table-column :formatter="defaultTableColumnDate" label="模版描述" align="center" prop="remark" />
      <el-table-column :formatter="defaultTableColumnDate" label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :formatter="defaultTableColumnDate" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            v-if="queryType!='平台模板'"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:template:remove']"
          >删除</el-button> -->
          <el-button
            size="mini"
            type="text"
            @click="handleForm(scope.row)"
            v-hasPermi="['system:template:edit']"
          >查看</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            v-if="queryType!='平台模板'"
            @click="handleDown(scope.row)"
          >下载</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <!-- <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    /> -->

    <!-- 添加或修改合同模版管理对话框 -->
    <el-dialog destroy-on-close :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模板文件" required>
          <el-upload
            :action="baseUrl + '/common/uploadTempFile'"
            :headers="{
              'Authorization': 'Bearer ' + getToken(),
            }"
            accept=".doc,.docx,.pdf"
            :on-success="handleSuccess"
            :limit="1">
            <div>
              <el-button size="small" type="primary">上传文件</el-button>
              <span slot="tip" class="el-upload__tip" style="margin-left: 20px;">支持扩展名：.doc .docx .pdf</span>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="模版描述" v-if="queryType=='平台模板'">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入模版描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { authenticationOrConsole } from "@/api/system/contract";
import { listGsTemplate, listPtTemplate, getTemplate, addTemplate, getTemplateUrl, delTemplate, listPtTemplateList } from "@/api/system/template";

export default {
  name: "Template",
  dicts: ['contract_type'],
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      getToken,
      fileUrl: '',
      fileName: '',
      queryType: '公司模板',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合同模版管理表格数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyId: null,
        templateName: null,
        templateType: null,
        templateUrl: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleForm(row) {
      getTemplateUrl({ contractUrl: row.id }).then(response => {
        const previewUrl = response.data.templates[0].previewUrl
        window.open(previewUrl)
      })
    },
    base64DownloadFile(url, fileName) {
      const link = document.createElement('a');
      link.href = url;
      link.download = fileName;
      link.target = "_blank"; // 可选，如果希望在新窗口中下载文件，请取消注释此行
      link.click();
    },
    handleDown(row) {
      if(this.queryType == '公司模板') {
        const url = this.baseUrl + row.templateUrl
        this.base64DownloadFile(url, row.templateUrl.split('/').slice(-1)[0])
      } else {
        getTemplateUrl({ contractUrl: row.id }).then(response => {
          const previewUrl = response.data.templates[0].previewUrl
          window.open(previewUrl)
        })
      }
    },
    handleSuccess(file) {
      this.fileUrl = file.fileName
      this.fileName = file.newFileName
    },
    /** 查询合同模版管理列表 */
    getList() {
      this.loading = true;
      if(this.queryType == '公司模板') {
        listPtTemplateList({userFlowTypeId: 'yDtIXUU2wlypwuUELw5Ix1csMmNOumuf', systemType: '公司'}).then(response => {
          this.templateList = response.data;
          this.templateList.forEach( t => {
            t.id = t.templateId
            t.templateUrl = t.templateId
            t.remark = t.description
            t.createTime = new Date(t.createdOn * 1000)
          })
          this.loading = false;
        });
        // listGsTemplate({...this.queryParams, templateType: '合同管理',}).then(response => {
        //   this.templateList = response.rows;
        //   this.total = response.total;
        //   this.loading = false;
        // });
      } else {
        listPtTemplateList({userFlowTypeId: 'yDtIXUU2wlypwuUELw5Ix1csMmNOumuf', systemType: '平台'}).then(response => {
          this.templateList = response.data;
          this.templateList.forEach( t => {
            t.id = t.templateId
            t.templateUrl = t.templateId
            t.remark = t.description
            t.createTime = new Date(t.createdOn * 1000)
          })
          this.loading = false;
        });
        // listPtTemplate({
        //   ...this.queryParams,
        //   limit: this.queryParams.pageSize,
        //   offset: this.queryParams.pageNum,
        //   userFlowTypeId: 'yDtIXUU2wlypwuUELw5Ix1csMmNOumuf'
        // }).then(response => {
        //   this.templateList = response.data.templates;
        //   this.templateList.forEach(t => {
        //     t.id = t.templateId
        //     t.remark = t.description
        //     t.createTime = new Date(t.createdOn * 1000)
        //   })
        //   this.total = response.data.totalCount;
        //   this.loading = false;
        // });
      }
    },
    handleClick(tab, event) {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        companyId: null,
        templateName: null,
        templateType: null,
        templateUrl: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.fileUrl = ''
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.fileUrl = ''
      this.open = true;
      this.title = "添加合同模版管理";
    },
    async jumpDZQ() {
      const res = await authenticationOrConsole({})
      window.open(res.data.pc)
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTemplate(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改合同模版管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if(!this.fileUrl) {
        this.$modal.msg(`请上传文件!`);
        return
      }
      const params = {
        ...this.form,
        templateUrl: this.fileUrl,
        templateName: this.fileName,
        templateType: '合同管理'
      }
      if(this.queryType == '公司模板') {
        addTemplate(params).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      } else {
        // addTemplatePt(params).then(response => {
        //   this.$modal.msgSuccess("新增成功");
        //   this.open = false;
        //   this.getList();
        // });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除合同模版管理编号为"' + ids + '"的数据项？').then(function() {
        return delTemplate(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/template/export', {
        ...this.queryParams
      }, `template_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
